/* eslint-disable no-use-before-define */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { FormattedMessage} from 'react-intl';
import { stripesConnect, IfPermission } from '@folio/stripes/core';
import get from 'lodash/get';
import { MultiColumnList, Button, Checkbox } from '@folio/stripes/components';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import SearchForm from '../../components/party-reserve/search-form';
import UrgentNotify from '../../components/party-reserve/urgent-notify';
class ReaderAppointmentList extends Component {
    static manifest = Object.freeze({

      reserveQuery: { initialValue: '' },
      resultCount: { initialValue: 10 },
      registrationRecords: {
        type: 'okapi',
        path: 'party/reserve',
        recordsRequired: '%{resultCount}',
        perRequest: 10,
        limitParam: 'limit',
        records: 'reserveGroup',
        GET: {
          params: {
            query: '( isDel = 0 %{reserveQuery} ) sortby reserveDate/sort.descending '
          }
        }

      },
      activityRegistrationHttpInvoke: {
        type: 'okapi',
        accumulate: true,
        path: () => 'party/reserve',

      },

      activityNotify: {
        type: 'okapi',
        accumulate: true,
        path: () => 'party/urgent_notify',

      }
    });

    static propTypes = {
      stripes: PropTypes.shape({
        logger: PropTypes.object
      }).isRequired,
      resources: PropTypes.object,
      mutator: PropTypes.shape({

        reserveQuery: PropTypes.string,
        activityRegistrationHttpInvoke: PropTypes.shape({
          PUT: PropTypes.func.isRequired,
          POST: PropTypes.func.isRequired,
          GET: PropTypes.func.isRequired,
          DELETE: PropTypes.func.isRequired
        }),

        activityNotify:PropTypes.shape({
          POST: PropTypes.func.isRequired,
        })
      }).isRequired,
      labelName: PropTypes.object,
      toModel:PropTypes.func,
      intl:PropTypes.object
    };

    constructor(props) {
      super(props);
      this.logger = props.stripes.logger;
      this.log = this.logger.log.bind(this.logger);
      this.state = {
        searchForm: {},
        editOpen: false,
        editParams: {},
        ascriptionList: [],
        optionCategoryList: [],
        searchFlag:true,
        isAllChecked: false,
        checkedState: {},
        sendMsgLength:0,
        sendMsg:'',
        selected: [],
        urgentNotifyOpen:false,
        waitOpen:false,
        operator: {}
      };
      this.label = this.props.labelName;
    }

    componentDidMount() {
      this.source = new StripesConnectedSource(this.props, this.logger);
      const { currentUser } = this.props.okapi;
      if (currentUser) {
        this.setState({
          operator: currentUser
        });
      }
    }

    componentDidUpdate() {
      this.source.update(this.props, 'registrationRecords');
    }

    componentWillUnmount() {
      const { mutator, resources } = this.props;

      mutator.reserveQuery.replace('');
    }

    search = ({ requestPreferences, creds, ...formData }) => {
      const { mutator } = this.props;
      if (!this.state.searchFlag) {
        console.log('页面防抖墙。。。');
        return false;
      }

      let query = '';
      if (formData) {
        if (formData.status) {
          query += ` and status == ${formData.status} `;
        }
        if (formData.partyName) {
          query += ` and partyName == *${formData.partyName}* `;
        }
        if (formData.readerName) {
          query += ` and readerReserveGroup == *"name"*: *"${formData.readerName}"* `;
        }
        if (formData.readerAccount) {
          query += ` and readerReserveGroup == *"barcode"*: *"${formData.readerAccount}"* `;
        }
        if (!!formData.partyStartDate && !formData.partyEndDate) {
          query += ` and partyStartDate >= ${moment(new Date(formData.partyStartDate)).format('YYYY-MM-DD')} 00:00:00 `;
          query += ` and partyStartDate <= ${moment(new Date(formData.partyStartDate)).format('YYYY-MM-DD')} 23:59:59 `;
        }
        if (!!formData.partyEndDate && !formData.partyStartDate) {
          query += ` and partyEndDate >= ${moment(new Date(formData.partyEndDate)).format('YYYY-MM-DD')} 00:00:00 `;
          query += ` and partyEndDate <= ${moment(new Date(formData.partyEndDate)).format('YYYY-MM-DD')} 23:59:59 `;
        }
        if (!!formData.partyStartDate && !!formData.partyEndDate) {
          query += ` and partyStartDate >= ${moment(new Date(formData.partyStartDate)).format('YYYY-MM-DD')} 00:00:00 `;
          query += ` and partyEndDate <= ${moment(new Date(formData.partyEndDate)).format('YYYY-MM-DD')} 23:59:59 `;
        }
      }

      mutator.reserveQuery.replace(query);
      if (this.source) {
        this.source.update(this.props, 'registrationRecords');
        this.setState({
          searchForm: formData,
          searchFlag: false
        });
        setTimeout(() => {
          this.setState({
            searchFlag: true
          });
        }, 300);
      }
    };

    moreData = () => {
      if (this.source) {
        this.source.fetchMore(10);
      }
    };

    updateData = item => {
      const {intl} = this.props;
      const {operator} = this.state;

      let request = item;
      request.status = 1;
      request.operator = operator;
      request.isDel = 0;
      delete request.rowIndex;
      delete request.operator.addresses;
      delete request.operator.preferredContactTypeId;
      delete request.operator.servicePoints;
      delete request.operator.curServicePoint;
      delete request.operator.dateOfBirth;
      // eslint-disable-next-line no-restricted-globals
      if (confirm(intl.formatMessage({id:"ui-party.other.are.you.sure.you.want.to.do.this"}))) {
        const { PUT } = this.props.mutator.activityRegistrationHttpInvoke;

        PUT(request)
          .then(res => {
            this.source.update(this.props, 'registrationRecords');
          })
          .catch(e => e);
      }
    };

    allCheckToggle=() => {
      const {
        resources
      } = this.props;
      this.setState((prevState) => {
        const dataList = get(resources, 'registrationRecords.records', []);
        const selectedArray = [];
        const checkedState = prevState.checkedState;
        if (!prevState.isAllChecked) {
          dataList.forEach((value) => {
            selectedArray.push(value.id);
            checkedState[value.id] = true;
          });
          return { selected:selectedArray, isAllChecked:true, checkedState };
        } else {
          dataList.forEach((value) => {
            checkedState[value.id] = false;
          });
          return { selected:selectedArray, isAllChecked:false, checkedState };
        }
      });
    }

    checkChange=(e) => {
      const input = e.currentTarget;
      this.setState(prevState => {
        const selectedArray = prevState.selected;
        const checkedState = prevState.checkedState;
        if (input.checked) {
          selectedArray.push(input.value);
          checkedState[input.value] = true;
        } else {
          selectedArray.splice(selectedArray.indexOf(input.value), 1);
          checkedState[input.value] = false;
        }
        return {
          isAllChecked: false,
          selected: selectedArray,
          checkedState
        };
      });
    }

    /** *
     * 控制弹窗打开
     */
    openUrgentNotify=() => {
      const {intl} = this.props
      if (this.state.selected.length === 0) {
        alert( intl.formatMessage({id:"ui-party.other.please.select.at.least.one.registration.record"}));
        return false;
      }

      this.setState((prevState) => {
        const urgentNotifyOpen = !prevState.urgentNotifyOpen;

        return {
          urgentNotifyOpen,
          sendMsgLength:0
        };
      });
    }
   closeUrgentNotify=() => {
     this.setState((prevState) => {
       const urgentNotifyOpen = false

       return {

         sendMsgLength:0,
         urgentNotifyOpen,
         selected:[],
         isAllChecked:false, checkedState:[]
       };
     });
   }
    render() {
      const { resources, toModel ,intl} = this.props;
      const able = document.getElementsByClassName('mclScrollable---IM56u');
      if (able && able[0]) {
        able[0].style.width = '102%';
      }

      const totalCount = this.source ? this.source.totalCount() : 0;
      const dataList = get(resources, 'registrationRecords.records', []);
      const formatter = {
        checkBox: <Checkbox checked={this.state.isAllChecked} onChange={this.allCheckToggle} />,
        serialNumber:  <FormattedMessage id="ui-party.loans.columns.serialNumber" />,
        partyName:  <FormattedMessage id="ui-party.loans.columns.party.partyName" />,
        readerAccount:  <FormattedMessage id="ui-party.loans.columns.readerAccount" />,
        readerName:  <FormattedMessage id="ui-party.loans.columns.readerName" />,
        registrationChannel:  <FormattedMessage id="ui-party.loans.columns.reserve.channel" />,
        status:  <FormattedMessage id="ui-party.loans.columns.reserve.status" />,
        registrationDateTime: <FormattedMessage id="ui-party.loans.columns.reserve.date" />,
        activityDateTime:  <FormattedMessage id="ui-party.loans.columns.reserve.partyDate" />,
        edit:  <FormattedMessage id="ui-party.loans.columns.operating" />,

      };

      return (
        <div>
          <UrgentNotify urgentNotifyOpen={this.state.urgentNotifyOpen} closeUrgentNotify={this.closeUrgentNotify} selected={this.state.selected} list={dataList}/>

          <SearchForm onSubmit={this.search} add={this.add} {...this.props} changeUrgentNotify={this.openUrgentNotify} />
          <MultiColumnList
            interactive={false}
            height={500}
            isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
            totalCount={totalCount}
            virtualize
            contentData={dataList}
            onNeedMoreData={this.moreData}
            columnMapping={formatter}
            pagingType="click"
            columnWidths={{
              checkBox: '5%',
              serialNumber: '50px',
              name: '300px',
              readerAccount: '120px',
              readerName: '100px',
              registrationChannel: '100px',
              status: '100px',
              registrationDateTime: '200px',
              activityDateTime: '200px',
              edit: '100px'
            }}
            visibleColumns={[
              'checkBox',
              'serialNumber',
              'partyName',
              'readerAccount',
              'readerName',
              'registrationChannel',
              'status',
              'registrationDateTime',
              'activityDateTime',
              'edit'
            ]}
            formatter={{
              checkBox: item => {
                return (
                  <Checkbox name="selectList" checked={this.state.checkedState[item.id]} onClick={this.checkChange} value={item.id} />
                );
              },
              partyName: item => [
                <div
                  title={item.partyName}
                  style={{
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}
                >
                  {item.partyName}
                </div>
              ],
              serialNumber: item => [<span>{item.rowIndex + 1}</span>],
              readerAccount: item => [
                <div
                  title={item.readerReserveGroup[0].barcode}
                  style={{
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}
                >
                  {item.readerReserveGroup[0].barcode}
                </div>
              ],
              readerName: item => [
                <div
                  title={item.readerReserveGroup[0].name}
                  style={{
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}
                >
                  {item.readerReserveGroup[0].name}
                </div>
              ],
              registrationChannel: item => {
                if (item.channel === 1) {
                  return <div><FormattedMessage id={"ui-party.loans.columns.channel.back.kitchen"}/></div>;
                } else if (item.channel === 2) {
                  return <div><FormattedMessage id={"ui-party.loans.columns.channel.wechat"}/></div>;
                } else if (item.channel === 3) {
                  return <div><FormattedMessage id={"ui-party.loans.columns.channel.web"}/></div>;
                }
              },

              activityDateTime: item => [
                <div
                  title={item.partyStartDate}
                  style={{
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}
                >
                  {item.partyStartDate}
                </div>
              ],
              status: item => {
                if (item.status === 0) {
                  return <div><FormattedMessage id={"ui-party.loans.columns.unreviewed"}/></div>;
                } else if (item.status === 1) {
                  return <div><FormattedMessage id={"ui-party.loans.columns.reviewed"}/></div>;
                } else if (item.status === 2) {
                  return <div><FormattedMessage id={"ui-party.loans.columns.reject"}/></div>;
                }
              },
              registrationDateTime: item => [<div>{item.reserveDate}</div>],
              edit: item => [
                item.status === 0 ? (
                  <IfPermission perm="ui-party.reserve.manage.view.modify">
                    <Button
                      onClick={() => {
                        this.updateData(item);
                      }}
                    >
                    <FormattedMessage id='ui-party.loans.columns.operating.approval'/>
                    </Button>
                  </IfPermission>
                ) : (
                  ''
                )
              ]
            }}
          />
        </div>
      );
    }
}

export default stripesConnect(ReaderAppointmentList);
